package com.example.myapplication.download;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;

/**
 * 描述：
 * 作者： shawn
 * 时间： 2023/7/414:33
 */
public class FileDownloader extends AsyncTask<String, Integer, String> {
        private static final int BUFFER_SIZE = 4096;
        private Context context;

        public FileDownloader(Context context) {
            this.context = context;
        }

        @Override
        protected String doInBackground(String... urls) {
            String url = urls[0];
            String fileName = urls[1];
            String fileDir = getSavePath();

            try {
                URL downloadUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
                connection.connect();

                int responseCode = connection.getResponseCode();
                if (responseCode != HttpURLConnection.HTTP_OK) {
                    return "Server returned HTTP " + responseCode + " " + connection.getResponseMessage();
                }

                File file = new File(fileDir, fileName);
                FileOutputStream outputStream = new FileOutputStream(file);
                InputStream inputStream = connection.getInputStream();

                byte[] buffer = new byte[BUFFER_SIZE];
                int bytesRead;
                long totalBytesRead = 0;
                long fileSize = connection.getContentLength();

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                    totalBytesRead += bytesRead;
                    publishProgress((int) ((totalBytesRead * 100) / fileSize));
                }

                outputStream.close();
                inputStream.close();

                return "File downloaded and saved to: " + file.getAbsolutePath();
            } catch (IOException e) {
                return e.getMessage();
            }
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            // You can update progress bar here if needed
            Log.d("FileDownloader", "onProgressUpdate:" + Arrays.toString(progress));
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Handle the downloaded file here
            Log.d("FileDownloader", result);
        }

    public String getSavePath() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_PICTURES, "xxxxxaaaaaaaaaaa");
            if (!file.exists()) {
                file.mkdirs();
            }
            return file.getAbsolutePath();
        } else {
//            return Environment.getExternalStorageDirectory().getPath();
            File parent = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "xxxxxaaaaaaaaaaa");
            if (!parent.exists()) {
                parent.mkdirs();
            }
            return parent.getAbsolutePath();
        }
    }
}

